#Copyright (c) 2012 Jordan Hollinger (jordan.hollinger@gmail.com)
#
#This library is free software; you can redistribute it and/or
#modify it under the terms of the GNU Library General Public
#License as published by the Free Software Foundation; either
#version 2 of the License, or (at your option) any later version.
#
#This library is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#Library General Public License for more details.
#
#You should have received a copy of the GNU Library General Public
#License along with this library; if not, write to the Free
#Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
#MA 02111-1307, USA

from fileauth import DAVAuthHandler

# Try to import crypt (Windows doesn't have it by default)
try:
    import crypt
except ImportError:
    try:
        import fcrypt as crypt
    except ImportError:
        sys.stderr.write("Cannot find a crypt module. Try http://carey.geek.nz/code/python-fcrypt/\n")
        sys.exit(1)

class HtpasswdAuthHandler(DAVAuthHandler):
    """
    Provides authentication from an htpasswd file
    """

    def get_userinfo(self,user,pw,command):
        """ authenticate user """

        # Try to read from the htpasswd file
        # Re-read htpasswd file each time, so that auth changes can be made without restarting server
        try:
            lines = open(self._config.DAV.htpasswd, 'r').readlines()
        except IOError:
            self._log('Authentication failed for user %s (%s unreadable)' % (user, self._config.DAV.htpasswd))

        # Loop through htpasswd entries until match is found
        for line in lines:
            htuser, pwhash = line.rstrip().split(':')
            if htuser == user:
              if pwhash == crypt.crypt(pw, pwhash):
                self._log('Successfully authenticated user %s' % user)
                return 1
              else:
                self._log('Authentication failed for user %s' % user)
                return 0

        self._log('Authentication failed for user %s' % user)
        return 0

